package com.smartplatform.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smartplatform.constants.ResultCode;
import com.smartplatform.dto.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 咕唧
 * @Date 2022/5/30 20:18
 * @Version 1.0
 */
//@Controller
public class MyLoginInterceptor implements HandlerInterceptor {
    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("user");
        if (user == null) {
            response.setContentType("application/json;charset=utf-8");
            //写入到浏览器
            String s = objectMapper.writeValueAsString(R.setResult(ResultCode.USER_NOT_LOGIN, "用户未登录", null));
            response.getWriter().write(s);
        }
        return user != null;
    }
}
